﻿using DatabaseProxy.Attributes;
using System.Reflection;
using System.Text;

namespace DatabaseProxy.ObjectSql;

public class ObjectSqlUpdater<T> where T : IDatabaseTable
{
    private static string _sql = "";
    private static PropertyInfo? _primaryKeyProperty = null;
    private static Dictionary<int, string> _sqlDictionary = new();
    public static PropertyInfo PrimaryKeyProperty
    {
        get
        {
            if (_primaryKeyProperty == null)
            {
                Type type = typeof(T);
                var properties = type.GetProperties();
                _primaryKeyProperty = properties.First(l => l.IsDefined(typeof(PrimaryKeyAttribute), false));
            }
            return _primaryKeyProperty;
        }
    }
    public static string Sql
    {
        get
        {
            if (string.IsNullOrEmpty(_sql))
            {
                Type type = typeof(T);
                var properties = type.GetProperties();
                string sql = $"""
                    UPDATE {Tool<T>.TableName} 
                    SET 
                    {
                        string.Join(",", Tool<T>.Columns
                        .Where(l => !l.Value.IsDefined(typeof(PrimaryKeyAttribute), false))
                        .Select(l => $"{l.Key}=@{l.Value.Name}"))
                    } 
                    WHERE {Tool<T>.PrimaryKeyName}=@{Tool<T>.PrimaryKeyProperty!.Name}
                """;
                _sql = sql;
            }
            return _sql;
        }
    }

    public static string MultipleSql(int count)
    {
        if (!_sqlDictionary.TryGetValue(count, out string? value))
        {
            StringBuilder sqlBuilder = new();
            for (int i = 0; i < count; i++)
            {
                string sql = $"""
                    Update {Tool<T>.TableName} 
                    SET 
                    {
                        string.Join(',', Tool<T>.Columns
                        .Where(l => !l.Value.IsDefined(typeof(PrimaryKeyAttribute), false))
                        .Select(l => $"{l.Key}=@{l.Value.Name + i}"))
                    } 
                    WHERE {Tool<T>.PrimaryKeyName}=@{Tool<T>.PrimaryKeyProperty!.Name + i};
                 """;
                sqlBuilder.Append(sql);
            }
            value = sqlBuilder.ToString();
            _sqlDictionary.Add(count, value);
        }
        return value;
    }
}
